import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadSwitchTest {
    static int c = 0;

    public static void main(String[] args) {
        testWithData();
    }

    private static void testWithData() {
        int threadSize = 100;
        CyclicBarrier barrier = new CyclicBarrier(threadSize);
        ExecutorService executorService = Executors.newFixedThreadPool(threadSize);
        for (int i = 0; i < threadSize; i++) {
            executorService.submit(new Runnable() {
                int s = 1;
                long l = 1000L;
                String d = "ssss";
                String p = s + l + d +"";

                @Override
                public void run() {
                    try {
                        barrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                    long start = System.currentTimeMillis();
                    System.out.println(p + start);
                    while (c < 10000000) {
                        increase();
                        if (c >= 10000000) {
                            System.out.println(c + "    " + (System.currentTimeMillis() - start));
                        }
                    }
                }
            });
        }
        System.out.println("---- " + c);
        executorService.shutdown();
    }

    private static void testWithoutData() {
        int threadSize = 100;
        ExecutorService executorService = Executors.newFixedThreadPool(threadSize);
        long nStart = System.currentTimeMillis();
        CyclicBarrier barrier = new CyclicBarrier(threadSize);
        for (int i = 0; i < threadSize; i++) {
            executorService.submit(() -> {
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                long start = System.currentTimeMillis();
                System.out.println(start - nStart);
                while (c < 10000000) {
                    increase();
                    if (c >= 10000000) {
                        System.out.println(c + "    " + (System.currentTimeMillis() - start));
                    }
                }
            });
        }
        System.out.println("---- " + c);
        executorService.shutdown();
    }


    synchronized static int increase() {
        return c++;
    }
}
